package com.example.externalstoreage;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.externalstoreage.utils.FileUtil;
import com.example.externalstoreage.utils.ToastHelper;

import java.io.File;
import java.io.FileInputStream;

public class ReadWriteImage extends AppCompatActivity implements View.OnClickListener {

    private ImageView ivImg;
    String fileName;
    private String targetPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_read_write_image);

        ivImg = findViewById(R.id.iv_img);
        findViewById(R.id.bt_read).setOnClickListener(this);
        findViewById(R.id.bt_copy).setOnClickListener(this);

        fileName = System.currentTimeMillis() + ".jpg";
        targetPath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString()
                + File.separatorChar + fileName;
    }

    // 从私有空间读取图片
    private void read() {
        // 方式一：输入流
        // Bitmap bitmap = FileUtil.readImage(targetPath);
        // ivImg.setImageBitmap(bitmap);
        // 方式二：
        // Bitmap bitmap = BitmapFactory.decodeFile(targetPath);
        // ivImg.setImageBitmap(bitmap);
        // 方式三：
        ivImg.setImageURI(Uri.parse(targetPath));
    }

    // 从资源目录中复制图片到私有空间
    private void copy() {
        // resource 从资源目录获取位图对象
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a);
        // 把位图对象保存为图片
        FileUtil.saveImage(targetPath, bitmap);
        ToastHelper.show(this, "保存图片成功");
        Log.d("zhoutao", targetPath);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.bt_copy) {
            copy();
        } else if (id == R.id.bt_read) {
            read();
        }
    }
}